package com.yex.job;

import com.yex.entity.MerchantOrderEntity;
import com.yex.entity.UserOrderEntity;
import com.yex.service.modify.order.MerchantOrderService;
import com.yex.service.modify.order.UserOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Configuration
@EnableScheduling
public class UserOrderJob {

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private MerchantOrderService merchantOrderService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    private List<MerchantOrderEntity> merchantOrderEntities;

    private MerchantOrderEntity _findById(Integer id) {
        for (MerchantOrderEntity item : merchantOrderEntities) {
            if (item.getId().compareTo(id) == 0) return item;
        }
        return null;
    }

    @Scheduled(cron = "*/10 * * * * ?")
    public void run() {
        List<UserOrderEntity> orderEntityList = userOrderService.getExpireOrders();
        if (orderEntityList != null && orderEntityList.size() > 0) {
            List<Integer> ids = new ArrayList<>();
            for (UserOrderEntity item : orderEntityList) {
                ids.add(item.getOrderId());
            }
            merchantOrderEntities = merchantOrderService.findOrderByIds(ids);
            for (UserOrderEntity item : orderEntityList) {
                MerchantOrderEntity merchantOrderEntity = _findById(item.getOrderId());
                if (merchantOrderEntity == null) return;
                try {
                    userOrderService.cancelOrderLogic(item, merchantOrderEntity);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("关闭用户超时订单:UserOrderJob->run", e);
                }
            }
        }
        System.out.println("执行清除超时订单定时任务");
    }

}
